package com.mashibing.lock;

import com.mashibing.conf.ZKUtil;
import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @author liuyno
 * @date 2021/3/8 - 23:30
 */
public class TestLock {
    ZooKeeper zk;


    @Before
    public void conn() {
        zk = ZKUtil.getZK();
    }

    @After
    public void disConn() {
        try {
            zk.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    @Test
    public void lockTest() {
        for (int i = 0; i < 10; i++) {
            //起10个线程模拟时态服务器，分别去抢锁
            new Thread() {
                @Override
                public void run() {
                    WatchAndCallback wac = new WatchAndCallback();
                    String threadName = Thread.currentThread().getName();
                    wac.setZk(zk);
                    wac.setThreadName(threadName);
                    //争抢锁
                    wac.tryLock();

                    //干活
                    System.out.println(threadName + "working");
                    System.out.println();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    //释放锁
                    wac.unLock();
                }
            }.start();
        }


        while (true) {


        }

    }
}
